<?php
namespace App\Helper;

class TimeHelper
{
    /**
     * 生成当前月份往前推N个月内的随机时间
     * @param int $months_back 需要往前推几个月（默认3）
     * @return string 格式：Y-m-d H:i:s
     */
    public static function randomRecentDatetime(int $months_back = 3): string
    {
        $now = time();
        $months = [];
        for ($i = 0; $i < $months_back; $i++) {
            $months[] = date('Y-n', strtotime("-$i month", $now));
        }
        list($y, $m) = explode('-', $months[array_rand($months)]);
        $d = rand(1, date('t', mktime(0, 0, 0, $m, 1, $y)));
        $h = rand(0, 23);
        $min = rand(0, 59);
        $s = rand(0, 59);
        return date('Y-m-d H:i:s', mktime($h, $min, $s, $m, $d, $y));
    }
}
